using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using MvcDemo09.Db;
using MvcDemo09.Models;

namespace MvcDemo09.Repository
{
    public class EfRepository<T> : IRepositoty<T> where T : BaseEntity
    {
        private readonly MvcDb _db;
        private readonly DbSet<T> _table;
        public IQueryable<T> Table {
            get{
                return _table as IQueryable<T>;
            }
        }
        public EfRepository()
        {
            _db = new MvcDb();
            _table = _db.Set<T>();
        }
        public void Delete(int id)
        {
            var entity = _table.Where(x=>x.Id==id && x.IsDel==false).FirstOrDefault();
            entity.IsDel=true;
            entity.UpTime=DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }

        public T GetById(int id)
        {
            var entity = _table.Where(x=>x.Id==id && x.IsDel==false).FirstOrDefault();
            return entity;
        }

        public void Insert(T entity)
        {
            entity.CreateTime=DateTime.Now;
            entity.UpTime=DateTime.Now;
            entity.IsActive=true;
            entity.IsDel=false;
            entity.DisplayorId=0;
            _table.Add(entity);
            _db.SaveChanges();
        }

        public void Update(T entity)
        {
           entity.UpTime=DateTime.Now;
           _table.Update(entity);
           _db.SaveChanges();
        }
    }
}